package cn.lizemin.toExcel;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author: lizemin
 * @version: 1.0
 */
public class MyUtil_Forth {
    //这是一个main方法,是程序的入口
    public static void main(String[] args) throws IOException {
        //还需要扩展到任意对象，属性未知，那怎么搞呢？，我不可能一个个去封装
        //还要是任意SQL

        Student stu1 = new Student("lizemin",29);
        Student stu2 = new Student("lize",18);
        Student stu3 = new Student("min",38);

        List<Student> students = new ArrayList<>();
        students.add(stu1);
        students.add(stu2);
        students.add(stu3);


        exportToExcel(students);

    }

    public static void exportToExcel(List<Student> objData) throws IOException {
        HSSFWorkbook wb = new HSSFWorkbook();
// / / Create an HSSFSheet object
        LocalDate now = LocalDate.now();
        DateTimeFormatter df = DateTimeFormatter.ISO_LOCAL_DATE;
        String str_date = df.format(now);
        HSSFSheet sheet = wb.createSheet(str_date);

        //获取属性
        Field[] fields = objData.get(0).getClass().getDeclaredFields();

        //填充属性
        HSSFRow row1 = sheet.createRow(0);
        for (int j = 0; j < fields.length; j++) {
            HSSFCell cell = row1.createCell(j);
            cell.setCellValue(String.valueOf(fields[j].getName()));
        }

        //先打印一行数据
        HSSFRow row2 = sheet.createRow(1);
        row2.createCell(0).setCellValue(objData.get(0).getName());
        row2.createCell(1).setCellValue(objData.get(0).getAge());


        //多行
        for (int i = 0; i < objData.size(); i++) {
            HSSFRow row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(objData.get(i).getName());
            row.createCell(1).setCellValue(objData.get(i).getAge());

        }

        //将文件名弄成时间戳
        LocalDateTime nowDateTime = LocalDateTime.now();

        DateTimeFormatter df2 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

        String str_nowDateTime = df2.format(nowDateTime);
        System.out.println(str_nowDateTime);
        str_nowDateTime = str_nowDateTime.replaceAll("-", "").replaceAll(":", "");
        StringBuilder stringBuilder = new StringBuilder(str_nowDateTime);

        StringBuilder sb = stringBuilder.replace(str_nowDateTime.indexOf("."), str_nowDateTime.indexOf(".") + 1, "");

        System.out.println(sb);
        FileOutputStream output = new FileOutputStream("C:\\Users\\15871\\Desktop\\mybatis\\" + sb + ".xls");


        wb.write(output);

        output.flush();

    }


}
